//
//  SettingsViewController.m
//  运营管理系统
//
//  Created by 杨毅 on 16/9/20.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "SettingsViewController.h"
#import "AppDelegate.h"
#import "ViewController.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "YXKit.h"
#import "EditionVC.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD.h"
@interface SettingsViewController ()<UIImagePickerControllerDelegate>
{
    UITextField *_OldPasswordTF;
    UITextField *_NewPassWordTF;
    UIView *_changeView;
    UIButton *_OK;
}
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@property (nonatomic,strong)UIScrollView *scorllView;
@property (nonatomic,strong)UIImageView *icon;
@property (nonatomic,strong)NSMutableArray *imageArray;
@end

@implementation SettingsViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
}
- (AFHTTPSessionManager *)manager{
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"设置";
    self.view.backgroundColor = [UIColor whiteColor];
    NSString *doucumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    //2.拼接上文件路径
    NSString *filtPath = [doucumentsPath stringByAppendingPathComponent:@"Log.txt"];
    //3.字典从文件中读取数据
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:filtPath];
    if (dic != nil) {
        
        if (![[dic objectForKey:@"username"] isKindOfClass:[NSNull class]] && ![[dic objectForKey:@"password"] isKindOfClass:[NSNull class]]) {
            self.loginAcc = [dic objectForKey:@"loginAcc"];
            self.username = [dic objectForKey:@"username"];
            self.telNum = [dic objectForKey:@"tel"];
            self.userID = [[dic objectForKey:@"userid"]integerValue];
            self.leveN = [dic objectForKey:@"levelN"];
            self.level = [[dic objectForKey:@"level"]integerValue];
            self.iconUrl = [dic objectForKey:@"iconurl"];
            self.userEmail = [dic objectForKey:@"emailStr"];
        }else{
    //读取保存在中间对象中的数据
    UIApplication *app = [UIApplication sharedApplication];
    
    AppDelegate *delegate = app.delegate;
    
    //获取注册界面保存的数据
    self.loginAcc = delegate.loginName;
    self.username = delegate.username;
    self.telNum = delegate.tel;
    self.userID = delegate.userId;
    self.leveN = delegate.levelName;
    self.level = delegate.level;
    self.iconUrl = delegate.iconUrl;
    self.userEmail = delegate.email;
        }
    }
    self.imageArray = [[NSMutableArray alloc]init];
    _scorllView = [[UIScrollView alloc]init];
    _scorllView.frame = CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT);
    _scorllView.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _scorllView.contentSize = CGSizeMake(kSCREEN_WIDTH, kSCREEN_HEIGHT+100);
    // 隐藏水平滚动条
    _scorllView.showsHorizontalScrollIndicator = NO;
    _scorllView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_scorllView];
    
    UIView *back1 = [[UIView alloc]initWithFrame:CGRectMake(0, 10, kSCREEN_WIDTH, 80)];
    back1.backgroundColor = [UIColor whiteColor];
    [_scorllView addSubview:back1];
    self.icon = [[UIImageView alloc]init];
    self.icon.frame = CGRectMake(9, 10, 60, 60);
    self.icon.layer.masksToBounds = YES;
    self.icon.layer.cornerRadius = 30;
    [self.icon sd_setImageWithURL:[NSURL URLWithString:self.iconUrl] placeholderImage:[UIImage imageNamed:@"user_icon1.png"]];
    [back1 addSubview:self.icon];
    UILabel *userNlab = [[UILabel alloc]initWithFrame:CGRectMake(76, 18, kSCREEN_WIDTH-76,21)];
    userNlab.text = [NSString stringWithFormat:@"用户名:%@",self.loginAcc];
    [back1 addSubview:userNlab];
    UIButton *choseIconBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    choseIconBtn.frame = CGRectMake(9, 10, 60, 60);
    [choseIconBtn addTarget:self action:@selector(choseIcon) forControlEvents:UIControlEventTouchUpInside];
    [back1 addSubview:choseIconBtn];
    //岗位
    UILabel *occupation = [[UILabel alloc]initWithFrame:CGRectMake(76, 47, kSCREEN_WIDTH-76, 21)];
    occupation.text = self.leveN;
    [back1 addSubview:occupation];
    
    UIView *back2 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(back1.frame)+10, kSCREEN_WIDTH, 80)];
    back2.backgroundColor = [UIColor whiteColor];
    [_scorllView addSubview:back2];
    //用户账号
    UILabel *userID = [[UILabel alloc]initWithFrame:CGRectMake(26, 17, (kSCREEN_WIDTH-36)/2, 21)];
    userID.text = [NSString stringWithFormat:@"用户账号:%@",self.username];
    [back2 addSubview:userID];
//    UILabel *leveID = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(userID.frame)+10, 17, (kSCREEN_WIDTH-36)/2, 21)];
//    leveID.text = [NSString stringWithFormat:@"等级:%ld",self.level];
//    [back2 addSubview:leveID];
    //用户邮箱
    UILabel *LXway = [[UILabel alloc]initWithFrame:CGRectMake(26, 46, kSCREEN_WIDTH-52, 21)];
    LXway.text = [NSString stringWithFormat:@"邮箱地址:%@",self.userEmail];
    [back2 addSubview:LXway];
    
    NSArray *imageArr = @[@"modify",@"exit",@"update"];
    NSArray *titleArr = @[@"修改密码",@"退出登录",@"关于运营系统"];
    for (NSInteger i = 0; i < 3; i++) {
        UIView *back3 = [[UIView alloc]initWithFrame:CGRectMake(0, 190+(i * (50+10)), kSCREEN_WIDTH, 50)];
        back3.backgroundColor = [UIColor whiteColor];
        [_scorllView addSubview:back3];
        UIImageView *leftImage = [[UIImageView alloc]initWithFrame:CGRectMake(24, 5, 40, 40)];
        leftImage.image = [[UIImage imageNamed:imageArr[i]]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [back3 addSubview:leftImage];
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(leftImage.frame)+5, 14,150, 21)];
        lab.text = titleArr[i];
        [back3 addSubview:lab];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, kSCREEN_WIDTH, 50);
        btn.tag = 1001+i;
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [back3 addSubview:btn];
    }



    

    
}
- (void)btnClick:(UIButton *)sender{

    if (sender.tag == 1002) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您是否要退出登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *OkAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            //1.获取Document(存放持久保存的数据)文件夹路径
            //参数1:查找的文件路径
            //参数2:在那个域中查找
            //参数3:是否显示详细路径
            NSString *doucumentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
            //2.拼接上文件路径
            NSString *filtPath = [doucumentsPath stringByAppendingPathComponent:@"Log.txt"];
            //删除文件
            NSFileManager *fileManager = [[NSFileManager alloc]init];
            [fileManager removeItemAtPath:filtPath error:nil];
            
            ViewController *login = [[ViewController alloc]init];
            [self.navigationController pushViewController:login animated:YES];

        }];
    
        [alert addAction:cancelAction];
        [alert addAction:OkAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else if(sender.tag == 1001){
        
                _changeView = [[UIView alloc]init];
                _changeView.backgroundColor = [UIColor whiteColor];
                _changeView.layer.shadowColor = [UIColor grayColor].CGColor;
                _changeView.layer.shadowOffset = CGSizeMake(0, 0);
                _changeView.layer.shadowOpacity = 1.0f;
                [self.view addSubview:_changeView];
                [_changeView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.center.equalTo(self.view);
                    make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH-80, kSCREEN_HEIGHT/3));
                }];
                UILabel *user = [[UILabel alloc]initWithFrame:CGRectMake(5, 20, 60, 30)];
                user.text = @"原密码";
                user.textColor = UIColorFromRGB(0x4d4d4d);
                [_changeView addSubview:user];
                _OldPasswordTF = [[UITextField alloc]initWithFrame:CGRectMake(70, 20, kSCREEN_WIDTH-155, 30)];
                _OldPasswordTF.placeholder = @"输入原始密码";
                _OldPasswordTF.clearButtonMode = UITextFieldViewModeAlways;
                _OldPasswordTF.secureTextEntry = YES;
                [_changeView addSubview:_OldPasswordTF];
                UIView *line1 = [[UIView alloc]initWithFrame:CGRectMake(70, 51, kSCREEN_WIDTH-155, 1)];
                line1.backgroundColor = UIColorFromRGB(0xb6b6b6);
                [_changeView addSubview:line1];
                UILabel *pass = [[UILabel alloc]initWithFrame:CGRectMake(5, 61, 60, 30)];
                pass.text = @"新密码";
                pass.textColor = UIColorFromRGB(0x4d4d4d);
                [_changeView addSubview:pass];
                _NewPassWordTF = [[UITextField alloc]initWithFrame:CGRectMake(70, 61, kSCREEN_WIDTH-155, 30)];
                _NewPassWordTF.placeholder = @"输入新密码";
                _NewPassWordTF.clearButtonMode = UITextFieldViewModeAlways;
                _NewPassWordTF.secureTextEntry = YES;
                [_changeView addSubview:_NewPassWordTF];
                UIView *line2 = [[UIView alloc]initWithFrame:CGRectMake(70, 92, kSCREEN_WIDTH-155, 1)];
                line2.backgroundColor = UIColorFromRGB(0xb6b6b6);
                [_changeView addSubview:line2];
        
                UILabel *lab = [[UILabel alloc]init];
                lab.text = @"隐藏密码";
                lab.font = [UIFont systemFontOfSize:12.0];
                lab.textColor = UIColorFromRGB(0x4d4d4d);
                [_changeView addSubview:lab];
                [lab mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.right.equalTo(_changeView.mas_right).offset(-10);
                    make.top.equalTo(line2.mas_bottom).offset(20);
                    make.size.mas_equalTo(CGSizeMake(75, 21));
                }];
                UIImage *check = [UIImage imageNamed:@"check"];
                UIImage *uncheck = [UIImage imageNamed:@"uncheck"];
                UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
                btn.selected = YES;
                [btn setImage:uncheck forState:UIControlStateNormal];
                [btn setImage:check forState:UIControlStateSelected];
                [btn addTarget:self action:@selector(selectedChange:) forControlEvents:UIControlEventTouchUpInside];
                [_changeView addSubview:btn];
                [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerY.equalTo(lab);
                    make.right.equalTo(lab.mas_left).offset(0);
                    make.size.mas_equalTo(CGSizeMake(20, 20));
                }];
                UIButton *cancel = [UIButton buttonWithType:UIButtonTypeCustom];
                [cancel setTitle:@"取消" forState:UIControlStateNormal];
                cancel.backgroundColor = UIColorFromRGB(0xd50037);
                [cancel addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
                [_changeView addSubview:cancel];
                [cancel mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(_changeView).offset(0);
                    make.left.equalTo(_changeView).offset(0);
                    make.size.mas_equalTo(CGSizeMake((kSCREEN_WIDTH-80)/2, 40));
                }];
                _OK = [UIButton buttonWithType:UIButtonTypeCustom];
                [_OK setTitle:@"确定" forState:UIControlStateNormal];
                _OK.backgroundColor = UIColorFromRGB(0x2dd500);
                [_OK addTarget:self action:@selector(OKclick) forControlEvents:UIControlEventTouchUpInside];
                [_changeView addSubview:_OK];
                [_OK mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.bottom.equalTo(_changeView).offset(0);
                    make.right.equalTo(_changeView.mas_right).offset(0);
                    make.size.mas_equalTo(CGSizeMake((kSCREEN_WIDTH-80)/2, 40));
                }];

    }else{
    
        EditionVC *editVC = [[EditionVC alloc]init];
        [self.navigationController pushViewController:editVC animated:YES];
    }
}
//选择头像上传的btn点击事件
- (void)choseIcon
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        [self showAlert:@"温馨提示" message:@"请打开访问相机权限" actionWithTitle:@"我知道了"];
    }else{
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"选择照片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *album = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {// 从相册选择
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        
        //通过代理方法来获取用户选择的照片
        //UIImagePickerControllerDelegate
        
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];

    }];
    UIAlertAction *photo = [UIAlertAction actionWithTitle:@"拍照上传" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {// 拍照
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }];
    UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    [alertVc addAction:album];
    [alertVc addAction:photo];
    [alertVc addAction:cancle];
    [self presentViewController:alertVc animated:YES completion:nil];
    }
}
//当用户选择完图片后会执行的方法,在该方法内获取用户选择的照片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //存储图片
    if ([[info objectForKey:UIImagePickerControllerMediaType]isEqualToString:(__bridge NSString*)kUTTypeImage]) {
        UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
        [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
        UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    }else{
    
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{
    NSSLog(@"保存到相册");
}
//保存头像
- (void)saveImage:(UIImage *)image{
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    //NSLog(@"imageFile->>%@",imageFilePath);
    success = [fileManager fileExistsAtPath:imageFilePath];
    if (success) {
        success = [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    //更换图片尺寸
    UIImage *smallImage = [self scaleFromImage:image toSize:CGSizeMake(60.0f, 60.0f)];
//    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(60, 60)];
    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    UIImage *selfPhoto = [UIImage imageWithContentsOfFile:imageFilePath];//读取文件
    self.icon.image = selfPhoto;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.imageArray removeAllObjects];
            [self.imageArray addObject:selfPhoto];
            [self IconUp];
        });
    });
    
    
}
// 改变图像的尺寸，方便上传服务器
- (UIImage *) scaleFromImage: (UIImage *) image toSize: (CGSize) size
{
    if([[UIScreen mainScreen] scale] == 2.0){
        UIGraphicsBeginImageContextWithOptions(size, NO, 2.0);
        //解决图片模糊的操作
    }else{
        UIGraphicsBeginImageContext(size);
    }

    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}
////保持原始图片的长宽比，生成需要尺寸的图片
//- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
//{
//    UIImage *newimage;
//    if (nil == image) {
//        newimage = nil;
//    }
//    else{
//        CGSize oldsize = image.size;
//        CGRect rect;
//        if (asize.width/asize.height > oldsize.width/oldsize.height) {
//            rect.size.width = asize.height*oldsize.width/oldsize.height;
//            rect.size.height = asize.height;
//            rect.origin.x = (asize.width - rect.size.width)/2;
//            rect.origin.y = 0;
//        }
//        else{
//            rect.size.width = asize.width;
//            rect.size.height = asize.width*oldsize.height/oldsize.width;
//            rect.origin.x = 0;
//            rect.origin.y = (asize.height - rect.size.height)/2;
//        }
//        UIGraphicsBeginImageContext(asize);
//        CGContextRef context = UIGraphicsGetCurrentContext();
//        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
//        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
//        [image drawInRect:rect];
//        newimage = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//    }
//    return newimage;
//}
//头像上传
- (void)IconUp{
    

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_IconURL parameters:@{userid:[NSString stringWithFormat:@"%ld",self.userID]} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        NSData *imageData =UIImageJPEGRepresentation(self.imageArray[0], 0.5);
        CGFloat dataBytes = imageData.length/1000.0;
        CGFloat maxQuality = 0.5f;
        CGFloat lastData = dataBytes;
        while (dataBytes > 300 && maxQuality > 0.1f) {
            maxQuality = maxQuality - 0.1f;
            imageData = UIImageJPEGRepresentation(self.imageArray[0], maxQuality);
            dataBytes = imageData.length / 1000.0;
            if (lastData == dataBytes) {
                break;
            }else{
                lastData = dataBytes;
            }
        }
        NSLog(@"%f",dataBytes);
        //if (dataBytes<300 || dataBytes == 300) {
        
        NSString *fileName = [NSString  stringWithFormat:@"image%d.jpg", 0];
        [formData appendPartWithFileData:imageData name:@"GZLR" fileName:fileName mimeType:@"image/jpeg"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSInteger status = [dic[@"status"]integerValue];
        if (status == 1) {
            [self showAlert:@"温馨提示" message:dic[@"message"] actionWithTitle:@"确定"];
        }else{
            [self showAlert:@"温馨提示" message:dic[@"message"] actionWithTitle:@"确定"];
        }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        //        NSSLog(@"%ld",(long)responses.statusCode);
        if (status >=500) {
            [self showAlert:@"上传失败" message:@"服务器出错" actionWithTitle:@"我知道了"];
        }else{
            [self showAlert:@"上传失败" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];
}
//修改密码
- (void)cancelClick{
    
    [_changeView removeFromSuperview];
}
- (void)OKclick{
    
    [UIView animateWithDuration:0 delay:1.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        _OK.userInteractionEnabled = NO;
    } completion:^(BOOL finished) {
        _OK.userInteractionEnabled = YES;
    }];
    if (_OldPasswordTF.text.length == 0 || _NewPassWordTF.text.length == 0){
    
        [self showAlert:@"请完善信息" message:nil actionWithTitle:@"确定"];
    }else{
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        self.manager.requestSerializer.timeoutInterval = 15;
    [_manager POST:K_passWChange parameters:@{userid:[NSString stringWithFormat:@"%ld",self.userID],Newpw:_NewPassWordTF.text,Oldpw:_OldPasswordTF.text} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

        NSInteger state;
        state = [dic[@"status"]integerValue];

        if (state == 1) {
            
            //延时操作
            [UIView animateWithDuration:0 delay:2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                
                [[YXAlertHUD stateHUDWithHUDTyep:0 message:@"修改成功" textColor:[UIColor blackColor] iconColor:[UIColor greenColor]] show];
                [_changeView removeFromSuperview];
                
            } completion:^(BOOL finished) {
                
                ViewController *login = [[ViewController alloc]init];
                [self.navigationController pushViewController:login animated:YES];
            }];

            
        }else{
            
            [self showAlert:@"提交失败" message:dic[@"message"] actionWithTitle:@"我知道了"];
        }
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        //        NSSLog(@"%ld",(long)responses.statusCode);
        if (status >=500) {
            [self showAlert:@"提交失败" message:@"服务器出错" actionWithTitle:@"我知道了"];
        }else{
            [self showAlert:@"提交失败" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];
    }
}
#pragma mark 封装提示框
-(void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)selectedChange:(UIButton *)sender{
    
    BOOL isSelected = sender.isSelected;
    if (isSelected)
    {
        //将当前状态设置为normal
        sender.selected = NO;
        _NewPassWordTF.secureTextEntry = NO;
        _OldPasswordTF.secureTextEntry = NO;
    }
    else
    {
        sender.selected = YES;
        _NewPassWordTF.secureTextEntry = YES;
        _OldPasswordTF.secureTextEntry = YES;
    }

}
- (void)back{

    [self.navigationController popViewControllerAnimated:YES];
}



@end
